package com.hpe.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpe.dao.BigQuestionMapper;
import com.hpe.dao.ExamMapper;
import com.hpe.dao.ScoreMapper;
import com.hpe.pojo.*;
import com.hpe.service.ScoreService;
import com.hpe.util.DownloadUtil;
import com.hpe.util.ExcelUtil;
import com.hpe.util.ServerResponse;
import com.hpe.util.ToolUtil;
import com.hpe.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:TangWenhao
 * @Description:
 * @Date:19:05 2017/9/25
 */
@Service
public class ScoreServiceImpl implements ScoreService {

    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private BigQuestionMapper bigQuestionMapper;
    @Autowired
    private ExamMapper examMapper;
    private Logger logger = LoggerFactory.getLogger(ScoreServiceImpl.class);

    @Override
    public ServerResponse<PageInfo> findAllPapers( int stuclassId, int id,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ReadOverPapers> allPapers= scoreMapper.findPaper(stuclassId,id);
        PageInfo pageInfo = new PageInfo(allPapers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    private List<LSReadOverpapers> lsFindAllpaper(Integer deptName,Integer queType,Integer eId,String bqId){
        List<LSReadOverpapers> oldList = scoreMapper.lsFindAllPaper(deptName,eId,bqId);
        //循环拆分
        //拆分之后的数据保存在newList中
        List<LSReadOverpapers> newList = new ArrayList<LSReadOverpapers>();
        for(int i=0;i<oldList.size();i++) {
            LSReadOverpapers old = oldList.get(i);
            String name = old.getExamName();
            int deptname = old.getDirection();
            String contentTitle = old.getContentTitle();
            String contentAns = old.getContentans();
            String time = old.getTesttime();
            double score = old.getScore1();
            double score1 = old.getScore2();
            double score2 = old.getScore3();
            double scoreb = old.getScoreb();
            int testId = old.geteId();
            int studentId = old.getsId();
            int status = old.getStatus();
            //未完成阅卷的题目
            String bigQueIds = old.getBigqueids();
            //所有的大题题目
            String allBigQueIds = old.getAllBigQuestionIds();
            String directionName = old.getDirectionName();
            String[] bigQuesions = allBigQueIds.split("\\,+");
            for (int j = 0; j < bigQuesions.length - 1; j++) {
                bigQuesions[j] = bigQuesions[j + 1];
            }
            //拆分 简单 和 编程   所有简答题在一起 所有 编程题在一起
            String[] titelsArrys = contentTitle.split("@@@");
            String[] ansArray = contentAns.split("@@@");


            if (ansArray.length > 1 && !"".equals(ansArray[0]) && !"".equals(ansArray[1])) {
                //简答和程序题都含有
                String sigTitle = titelsArrys[0];
                String codeTitle = titelsArrys[1];

                String sigAns = ansArray[0];
                String codeAns = ansArray[1];
                //queType是简答题  为1
                if (queType != null && queType == 1) {
                    //简答题  拆分
                    String[] titles1 = sigTitle.split("~");
                    String[] ans1 = sigAns.split("~");
                    for (int j = 0; j < titles1.length; j++) {
                        String smallTitle;
                        if (titles1[j].length() > 10) {
                            smallTitle = titles1[j].substring(0, 10);
                        } else {
                            smallTitle = titles1[j];
                        }
                        ;
                        newList.add(new LSReadOverpapers(studentId, deptname, queType, status, testId, time, titles1[j],
                                name, ans1[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[j]), allBigQueIds));
                    }
                }
                //queType是程序题
                else if (queType != null && queType == 2) {
                    //获取简答题的数目，得到编程题开始的题号
                    String[] titles1 = sigTitle.split("~");
                    int bqtiSize = titles1.length;
                    //程序题
                    String[] titles2 = codeTitle.split("~");
                    String[] ans2 = codeAns.split("~");
                    for (int j = 0; j < titles2.length; j++) {
                        String smallTitle;
                        if (titles2[j].length() > 10) {
                            smallTitle = titles2[j].substring(0, 10);
                        } else {
                            smallTitle = titles2[j];
                        }
                        newList.add(new LSReadOverpapers(studentId, deptname, queType, status, testId, time, titles2[j],
                                name, ans2[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[bqtiSize++]), allBigQueIds));
                    }
                } else {
                    //简答题 不指定查询类型的话
                    String[] titles1 = sigTitle.split("~");
                    String[] ans1 = sigAns.split("~");
                    int bqtisize = 0;
                    for (int j = 0; j < titles1.length; j++) {
                        String smallTitle;
                        if (titles1[j].length() > 10) {
                            smallTitle = titles1[j].substring(0, 10);
                        } else {
                            smallTitle = titles1[j];
                        }
                        newList.add(new LSReadOverpapers(studentId, deptname, 1, status, testId, time, titles1[j],
                                name, ans1[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[bqtisize++]), allBigQueIds));
                    }
                    //程序题
                    String[] titles2 = codeTitle.split("~");
                    String[] ans2 = codeAns.split("~");
                    for (int j = 0; j < titles2.length; j++) {
                        String smallTitle;
                        if (titles2[j].length() > 10) {
                            smallTitle = titles2[j].substring(0, 10);
                        } else {
                            smallTitle = titles2[j];
                        }
                        newList.add(new LSReadOverpapers(studentId, deptname, 2, status, testId, time, titles2[j],
                                name, ans2[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[bqtisize++]), allBigQueIds));
                    }
                }
            }
            else{
                if(!"".equals(ansArray[0])){
                    //只有简答题
                    String sigTitle = titelsArrys[0];
                    String sigAns = ansArray[0];
                    if(queType==null||queType == 1){
                        String[] titles1 = sigTitle.split("~");
                        String[] ans1 = sigAns.split("~");
                        for(int j=0;j<titles1.length;j++){
                            String smallTitle;
                            if(titles1[j].length()>10){
                                smallTitle = titles1[j].substring(0, 10);
                            }else{
                                smallTitle = titles1[j];
                            }
                            newList.add(  new LSReadOverpapers( studentId, deptname,  1, status,testId , time,  titles1[j],
                                    name,ans1[j], bigQueIds,score, score1, score2, scoreb,smallTitle,directionName,Integer.valueOf(bigQuesions[j]),allBigQueIds));
                        }
                    }

                }else{
                    if("".equals(ansArray[0])&&!"".equals(ansArray[1])) {
                        //只有编程题
                        String codeTitle = titelsArrys[1];
                        String codeAns = ansArray[1];
                        if (queType == null || queType == 2) {
                            String[] titles2 = codeTitle.split("~");
                            String[] ans2 = codeAns.split("~");
                            for (int j = 0; j < titles2.length; j++) {
                                String smallTitle;
                                if (titles2[j].length() > 10) {
                                    smallTitle = titles2[j].substring(0, 10);
                                } else {
                                    smallTitle = titles2[j];
                                }
                                newList.add(new LSReadOverpapers(studentId, deptname, 2, status, testId, time, titles2[j],
                                        name, ans2[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[j]), allBigQueIds));
                            }
                        }
                    }
                }
            }
        }
        List<LSReadOverpapers> list = new ArrayList<>(newList);
        //通过遍历page中所有list中的bigQueIds，设置某大题的批阅状态
        for(int i=0;i<list.size();i++){
            LSReadOverpapers o = list.get(i);
            BigQuestion bq = bigQuestionMapper.selectByPrimaryKey(o.getBigQuestionId());
            //获取标准答案
            list.get(i).setBzAns(bq.getContentans());
            //这题对应的分数
            Exam  exma = examMapper.selectByPrimaryKey(list.get(i).geteId());
            if(bq.getType()==1){
                //每道简答题分数
                list.get(i).setBqScore(exma.getScore1()/(exma.getQuestions().split(";")[1].split(",").length-1));
            }else{
                //每道编程题分数
                list.get(i).setBqScore(exma.getScore2()/(exma.getQuestions().split(";")[2].split(",").length-1));
            }
            //通过查询bigQueIds里面的id判断有没有被批阅
            if(o.getBigqueids().contains(","+Integer.toString(bq.getId())+",")){
                o.setStatus(0);
            }else{
                o.setStatus(1);
            }
        }
//        PageHelper.startPage(pageNum,pageSize);
//        PageInfo pageInfo = new PageInfo(list);
//        pageInfo.setList(oldList);
        return list;
    }
    @Override
    public ServerResponse<PageInfo> lsFindAllPapers(Integer deptName,Integer queType,int pageNum,int pageSize) {
                //原来的
//        List oldList = null;
//        oldList = scoreMapper.lsFindPaper(deptName);
        PageHelper.startPage(pageNum, pageSize);
        List<LSReadOverpapers> oldList = scoreMapper.lsFindPaper(deptName);
        //拆分之后的数据保存在newList中
        List<LSReadOverpapers> newList = new ArrayList<LSReadOverpapers>();
            if(oldList.size() == 0){
                PageInfo pageInfo = new PageInfo(oldList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            LSReadOverpapers old = oldList.get(0);
            String name = old.getExamName();
            int deptname = old.getDirection();
            String contentTitle = old.getContentTitle();
            String contentAns = old.getContentans();
            String time = old.getTesttime();
            double score = old.getScore1();
            double score1 = old.getScore2();
            double score2 = old.getScore3();
            double scoreb = old.getScoreb();
            int testId = old.geteId();
            int studentId = old.getsId();
            int status = old.getStatus();
            //未完成阅卷的题目
            String bigQueIds = old.getBigqueids();
            //所有的大题题目
            String allBigQueIds = old.getAllBigQuestionIds();
            String directionName = old.getDirectionName();
            String[] bigQuesions = allBigQueIds.split("\\,+");
            for (int j = 0; j < bigQuesions.length - 1; j++) {
                bigQuesions[j] = bigQuesions[j + 1];
            }
            //拆分 简单 和 编程   所有简答题在一起 所有 编程题在一起
            String[] titelsArrys = contentTitle.split("@@@");
            String[] ansArray = contentAns.split("@@@");


            if (ansArray.length > 1 && !"".equals(ansArray[0]) && !"".equals(ansArray[1])) {
                //简答和程序题都含有
                String sigTitle = titelsArrys[0];
                String codeTitle = titelsArrys[1];

                String sigAns = ansArray[0];
                String codeAns = ansArray[1];
                //queType是简答题  为1
                if (queType != null && queType == 1) {
                    //简答题  拆分
                    String[] titles1 = sigTitle.split("~");
                    String[] ans1 = sigAns.split("~");
                    for (int j = 0; j < titles1.length; j++) {
                        String smallTitle;
                        if (titles1[j].length() > 10) {
                            smallTitle = titles1[j].substring(0, 10);
                        } else {
                            smallTitle = titles1[j];
                        }
                        ;
                        newList.add(new LSReadOverpapers(studentId, deptname, queType, status, testId, time, titles1[j],
                                name, ans1[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[j]), allBigQueIds));
                    }
                }
                //queType是程序题
                else if (queType != null && queType == 2) {
                    //获取简答题的数目，得到编程题开始的题号
                    String[] titles1 = sigTitle.split("~");
                    int bqtiSize = titles1.length;
                    //程序题
                    String[] titles2 = codeTitle.split("~");
                    String[] ans2 = codeAns.split("~");
                    for (int j = 0; j < titles2.length; j++) {
                        String smallTitle;
                        if (titles2[j].length() > 10) {
                            smallTitle = titles2[j].substring(0, 10);
                        } else {
                            smallTitle = titles2[j];
                        }
                        newList.add(new LSReadOverpapers(studentId, deptname, queType, status, testId, time, titles2[j],
                                name, ans2[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[bqtiSize++]), allBigQueIds));
                    }
                } else {
                    //简答题 不指定查询类型的话
                    String[] titles1 = sigTitle.split("~");
                    String[] ans1 = sigAns.split("~");
                    int bqtisize = 0;
                    for (int j = 0; j < titles1.length; j++) {
                        String smallTitle;
                        if (titles1[j].length() > 10) {
                            smallTitle = titles1[j].substring(0, 10);
                        } else {
                            smallTitle = titles1[j];
                        }
                        newList.add(new LSReadOverpapers(studentId, deptname, 1, status, testId, time, titles1[j],
                                name, ans1[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[bqtisize++]), allBigQueIds));
                    }
                    //程序题
                    String[] titles2 = codeTitle.split("~");
                    String[] ans2 = codeAns.split("~");
                    for (int j = 0; j < titles2.length; j++) {
                        String smallTitle;
                        if (titles2[j].length() > 10) {
                            smallTitle = titles2[j].substring(0, 10);
                        } else {
                            smallTitle = titles2[j];
                        }
                        newList.add(new LSReadOverpapers(studentId, deptname, 2, status, testId, time, titles2[j],
                                name, ans2[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[bqtisize++]), allBigQueIds));
                    }
                }
            }
            else{
                if(!"".equals(ansArray[0])){
                //只有简答题
                    String sigTitle = titelsArrys[0];
                    String sigAns = ansArray[0];
                  if(queType==null||queType == 1){
                    String[] titles1 = sigTitle.split("~");
                    String[] ans1 = sigAns.split("~");
                    for(int j=0;j<titles1.length;j++){
                        String smallTitle;
                        if(titles1[j].length()>10){
                            smallTitle = titles1[j].substring(0, 10);
                        }else{
                            smallTitle = titles1[j];
                        }
                        newList.add(  new LSReadOverpapers( studentId, deptname,  1, status,testId , time,  titles1[j],
                                name,ans1[j], bigQueIds,score, score1, score2, scoreb,smallTitle,directionName,Integer.valueOf(bigQuesions[j]),allBigQueIds));
                    }
                }

            }else{
                    if("".equals(ansArray[0])&&!"".equals(ansArray[1])) {
                        //只有编程题
                        String codeTitle = titelsArrys[1];
                        String codeAns = ansArray[1];
                        if (queType == null || queType == 2) {
                            String[] titles2 = codeTitle.split("~");
                            String[] ans2 = codeAns.split("~");
                            for (int j = 0; j < titles2.length; j++) {
                                String smallTitle;
                                if (titles2[j].length() > 10) {
                                    smallTitle = titles2[j].substring(0, 10);
                                } else {
                                    smallTitle = titles2[j];
                                }
                                newList.add(new LSReadOverpapers(studentId, deptname, 2, status, testId, time, titles2[j],
                                        name, ans2[j], bigQueIds, score, score1, score2, scoreb, smallTitle, directionName, Integer.valueOf(bigQuesions[j]), allBigQueIds));
                            }
                        }
                    }
                }
           }
        List<LSReadOverpapers> list = new ArrayList<>(newList);
        //通过遍历page中所有list中的bigQueIds，设置某大题的批阅状态
        for(int i=0;i<list.size();i++){
            LSReadOverpapers o = list.get(i);
            o.setSmallTitle(HtmlUtils.htmlEscape(o.getSmallTitle()));
            BigQuestion bq = bigQuestionMapper.selectByPrimaryKey(o.getBigQuestionId());
            //获取标准答案
            list.get(i).setBzAns(bq.getContentans());
            //这题对应的分数
            Exam  exma = examMapper.selectByPrimaryKey(list.get(i).geteId());
            if(bq.getType()==1){
                //每道简答题分数
                list.get(i).setBqScore(exma.getScore1()/(exma.getQuestions().split(";")[1].split(",").length-1));
            }else{
                //每道编程题分数
                list.get(i).setBqScore(exma.getScore2()/(exma.getQuestions().split(";")[2].split(",").length-1));
            }
            //通过查询bigQueIds里面的id判断有没有被批阅
            if(o.getBigqueids().contains(","+Integer.toString(bq.getId())+",")){
                o.setStatus(0);
            }else{
                o.setStatus(1);
            }
        }
//        PageHelper.startPage(pageNum,pageSize);
//        PageInfo pageInfo = new PageInfo(list);
//        pageInfo.setList(oldList);
        PageInfo pageInfo = new PageInfo(oldList);
        pageInfo.setList(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse showUpdate(int sId, int examId) {
        return null;
    }

    @Override
    public Score findNextPaper(int stuClassId, int examId,int teaId) {
        return scoreMapper.findNextPaper(stuClassId,examId,teaId);
    }

    @Override
    public LSReadOverpapers lsFindNextPaper(Integer deptName, Integer queType,String bigQuestion,Integer eId) {
        //获取所有试卷
        List<LSReadOverpapers> allPaper = lsFindAllpaper( deptName, queType,eId,bigQuestion);
        //找到未改的试卷
        for(LSReadOverpapers paper:allPaper){
                if(paper.getStatus() == 0 && String.valueOf(paper.getBigQuestionId()).equals(bigQuestion)){
                return paper;
             }
            continue;
        }
        //全部改完
        return null;
    }


    @Override
    public Object lsUpdateScore(int examId, int sId, String type, String direct, String score,String bigQuestionId) {
        //通过题目查询题目id和类型
        BigQuestion bq = bigQuestionMapper.selectByPrimaryKey(Integer.valueOf(bigQuestionId));
        //通过试卷id获取试卷信息
        ScoreKey scoreKey = new ScoreKey(sId,examId);
        Score p = scoreMapper.selectByPrimaryKey(scoreKey);
        String bigQueIds = p.getBigqueids();
        //将papers表中的被批阅的大题的id去除,如果不包含该大题id，说明已经被批阅，不执行任何操作，直接到show
        if(bigQueIds.contains(","+Integer.toString(bq.getId())+",")){
            bigQueIds = bigQueIds.replace(",,"+Integer.toString(bq.getId())+",","");
            p.setBigqueids(bigQueIds);
            //把刚批完的题目分值加到相应试卷中
            if(!ToolUtil.containsOtherChar(score)){
                //通过type判断是简答还是程序题
                if(bq.getType()==1){
                    double score1 = Double.valueOf(score).doubleValue();
                    double score_ = p.getScore2()+score1;
                    p.setScore2(score_);
                }else if(bq.getType()==2){
                    double score_ = p.getScore3()+Double.valueOf(score).doubleValue();
                    p.setScore3(score_);
                }
            }
            //将改变的分值保存到数据库
                if(p.getBigqueids() == null ||p.getBigqueids().equals("")){
                    scoreMapper.updateBQAndStatusScore(p.getScore2(),p.getScore3(),p.getBigqueids(),p.getsId(),p.getExamId());
                }else{
                    scoreMapper.updateBQScore(p.getScore2(),p.getScore3(),p.getBigqueids(),p.getsId(),p.getExamId());
                }
            //解锁
            Score thisScore = findById(sId,examId);
            thisScore.setSpare("0");
            updatePagers(thisScore);
        }
        //改完这一题之后获取下一个要改的题
        Integer deptName = Integer.valueOf(direct);
        Integer queType = Integer.valueOf(type);
        LSReadOverpapers nextPaper = lsFindNextPaper(deptName,queType,bigQuestionId,examId);
        if(nextPaper == null){
            //全部改完了
            return "全部改完";
        }else{
            return nextPaper;
        }
    }

    @Override
    public ServerResponse insert(Score s) {
        return null;
    }

    @Override
    public ServerResponse updatePagers(Score s) {
        int result=scoreMapper.updateByPrimaryKeySelective(s);
        if(result <= 0) {
            return ServerResponse.createByErrorMsg("改卷失败");
        }
        return ServerResponse.createBySuccess("改卷成功");
    }

    @Override
    public Score findById(int sid,int examid) {
        ScoreKey scoreKey=new ScoreKey();
        scoreKey.setExamId(examid);
        scoreKey.setsId(sid);
        return scoreMapper.selectByPrimaryKey(scoreKey);
    }

    @Override
    public ServerResponse<PageInfo> findPaperByStudent(int id,String courseName,int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ExamHistory> allPapers= scoreMapper.findPaperByStudent(id,courseName);
        PageInfo pageInfo = new PageInfo(allPapers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public List<Score> getPaperByStudentId(int studentId, int testId) {
        List<Score> unAvailablePapers= scoreMapper.getPaperByStudentId(studentId, testId);
        return unAvailablePapers;
    }

    @Override
    public ServerResponse insertPapers(Score record) {
        int result=scoreMapper.insertSelective(record);
        if(result <= 0) {
            return ServerResponse.createByErrorMsg("答卷提交失败");
        }
        return ServerResponse.createBySuccess("提交成功");
    }

    @Override
    public ServerResponse<PageInfo> findUsualScores(int stuClassId, int testId, int sId,int pageNum, int  pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UsualScores> allPapers= scoreMapper.findUsualScores(stuClassId,testId,sId);
        PageInfo pageInfo = new PageInfo(allPapers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<PageInfo> findAvg(int stuClassId, int teaId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassScoreVO> allPapers= scoreMapper.teaFindClassAvgForExam(stuClassId,teaId);
        PageInfo pageInfo = new PageInfo(allPapers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<PageInfo> findEvaDetail(int classId, int examId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<EvaVo> details= scoreMapper.findEvaDetail(classId,examId);
        PageInfo pageInfo = new PageInfo(details);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public void outputExcelByEva(HttpServletRequest req, HttpServletResponse resp, int classId, int examId) throws Exception {
        List<EvaVo> details= scoreMapper.findEvaDetail(classId,examId);
        String[] beanProperty = { "ExamName", "CourseName", "sClassName", "StuName", "Score_1", "Score_2", "Score_3","Score_b","Score_m","Score_all"};
        String[] colName = {"考试名称", "课程名称", "班级名称", "学生姓名", "选择成绩", "简答成绩", "编程成绩","笔试总成绩","平时成绩","总成绩"};

        ExcelUtil excelUtil = new ExcelUtil("2007");

        ByteArrayOutputStream arrayOutputStream =
                excelUtil.getExcelStreamWithPointOutProperties(details.toArray(new EvaVo[details.size()]), beanProperty, colName, "汇总", "");

        new DownloadUtil().download(arrayOutputStream, resp, req, "汇总表-"+classId +"-"+examId+ ".xlsx");

    }

    @Override
    public void outputExcelByUsual(HttpServletRequest req, HttpServletResponse resp, int classId, int examId) throws Exception {
        List<UsualScores> details= scoreMapper.findUsualByClassAndExam(classId,examId);
        String[] beanProperty = { "TestName", "CourseName", "ClassName", "StuName","ScoreM"};
        String[] colName = {"考试名称", "课程名称", "班级名称", "学生姓名","平时成绩"};

        ExcelUtil excelUtil = new ExcelUtil("2007");

        ByteArrayOutputStream arrayOutputStream =
                excelUtil.getExcelStreamWithPointOutProperties(details.toArray(new UsualScores[details.size()]), beanProperty, colName, "汇总", "");

        new DownloadUtil().download(arrayOutputStream, resp, req, "汇总表-"+classId +"-"+examId+ ".xlsx");

    }

    @Override
    public ServerResponse<PageInfo> findUsualByStuExam(int stuClassId,int sId, int examsId,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UsualScores> details= scoreMapper.findUsualByStuExam(stuClassId,sId,examsId);
        PageInfo pageInfo = new PageInfo(details);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<PageInfo> findNextUsualScores(int stuClassId, int examId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UsualScores> details= scoreMapper.findNextUsualScores(stuClassId,examId);
        PageInfo pageInfo = new PageInfo(details);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public Integer findPractice(int sId) {
        UsualScores usualScores=scoreMapper.findPractice(sId);
        if(usualScores!=null) {
                String[] score = usualScores.getScoreArray().split(",");
                //计数器
                int total = 0;
                double sum = 0.0;
                for (int i = 0; i < score.length; i++) {
                    Double j = Double.parseDouble(score[i]);
                    if (j == 0) {
                        total++;
                    }
                    sum += j;
                }
                //最后求出平均值,把值为0的去掉
                double result;
                if (score.length - total > 0) {
                    result = sum / (score.length - total);
                } else {
                    result = 0;
                }
                int practice = (new Double(result)).intValue();
                if(practice>100){
                    practice=100;
                }
                return practice > 60 ? practice : 60;
        }
        return 60;
    }

    @Override
    public Integer countScores(String beginTime, String endTime) {
        return scoreMapper.countScore(beginTime,endTime).intValue();
    }

    @Override
    public String getAnsForPaper(int eId , int stuId , int bigQuestionId) {
        String resultAns = null;

        Score score = scoreMapper.selectByPrimaryKey(new ScoreKey(stuId, eId));
        //拆分答案
        String[] paperAns = score.getContentans().split("@@@");
        if(paperAns.length>1&&!"".equals(paperAns[0])){
        //简答题答案
        String[] bqt1Ans = paperAns[0].split("~");
        //编程题答案
        String[] bqt2Ans = paperAns[1].split("~");
        //合并答案
        String[] ans = new String[bqt1Ans.length + bqt2Ans.length];
        System.arraycopy(bqt1Ans, 0, ans, 0, bqt1Ans.length);
        System.arraycopy(bqt2Ans, 0, ans, bqt1Ans.length, bqt2Ans.length);
        //获取所有大题题号
        String allBigQueIds = score.getSpare1();
        String[] bigQuesions = allBigQueIds.split("\\,+");
        for (int j = 0; j < bigQuesions.length - 1; j++) {
            bigQuesions[j] = bigQuesions[j + 1];
        }
        //获取这一题的考生作答
        for (int i = 0; i < bigQuesions.length; i++) {
            if (Integer.valueOf(bigQuesions[i]) == bigQuestionId) {
                resultAns = ans[i];
                break;
            }
        }
    }else{
            if(paperAns.length>1&&"".equals(paperAns[0])){
                //试卷只出了编程题
                //编程题答案
                String[] bqt2Ans = paperAns[1].split("~");
                //合并答案
                //获取所有大题题号
                String allBigQueIds = score.getSpare1();
                String[] bigQuesions = allBigQueIds.split("\\,+");
                for (int j = 0; j < bigQuesions.length - 1; j++) {
                    bigQuesions[j] = bigQuesions[j + 1];
                }
                //获取这一题的考生作答
                for (int i = 0; i < bigQuesions.length; i++) {
                    if (Integer.valueOf(bigQuesions[i]) == bigQuestionId) {
                        resultAns = bqt2Ans[i];
                        break;
                    }
                }
            }else if(paperAns.length == 1){
                //试卷只出了简答题
                //编程题答案
                String[] bqt1Ans = paperAns[0].split("~");
                //合并答案
                //获取所有大题题号
                String allBigQueIds = score.getSpare1();
                String[] bigQuesions = allBigQueIds.split("\\,+");
                for (int j = 0; j < bigQuesions.length - 1; j++) {
                    bigQuesions[j] = bigQuesions[j + 1];
                }
                //获取这一题的考生作答
                for (int i = 0; i < bigQuesions.length; i++) {
                    if (Integer.valueOf(bigQuesions[i]) == bigQuestionId) {
                        resultAns = bqt1Ans[i];
                        break;
                    }
                }
            }
        }
        if(resultAns==null){
            return "不正常";
        }
        return resultAns;
    }

    @Override
    public ServerResponse loadinExcel(InputStream inputStream) throws Exception {
        ExcelUtil excelUtil = new ExcelUtil(inputStream, "2007");
        String[] propertyNames = { "TestName", "CourseName", "ClassName", "StuName","ScoreM"};

        Class<?>[] propertyTypes = {String.class, String.class, String.class, String.class, Double.class};
        List<UsualVo> usualScores = null;
        try {
            usualScores = excelUtil.readExcel(propertyNames, propertyTypes, UsualVo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("导入失败，请稍后重试");
        }
        return ServerResponse.createBySuccess("导入成功",usualScores);
    }

    @Override
    public ServerResponse findUsualByClassAndExam(int classId, int examId) {
        List<UsualScores> list = scoreMapper.findUsualByClassAndExam(classId,examId);
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse<PageInfo> findStuScore(String stuName,String other,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<EduScoreStuVO> allPapers= scoreMapper.findStuScore(stuName,other);
        PageInfo pageInfo = new PageInfo(allPapers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getRestetExamInfo() {
        //查询含有不及格考生的所有试卷
        List<ResetExamVo> resetExamVoList = scoreMapper.findResetScore();

        return ServerResponse.createBySuccess(resetExamVoList);
    }


}
